package com.fufan.mtsaas.modules.newtech.xjsyearaudit.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fufan.mtsaas.constant.DefaultConstant;
import com.fufan.mtsaas.modules.base.log.service.TSysLogSvc;
import com.fufan.mtsaas.modules.base.sysmsg.dao.TSysMessageDao;
import com.fufan.mtsaas.modules.base.sysmsg.model.TSysMessage;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.base.processinfo.dao.PProcessInfoDao;
import com.fufan.mtsaas.modules.base.processinfo.model.PProcessInfo;
import com.fufan.mtsaas.modules.newtech.xjstech.model.XjsTech;
import com.fufan.mtsaas.modules.newtech.xjstech.service.impl.XjsTechSvcImpl;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.bo.CirculationStatusBo;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.bo.ProcessItemBo;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.dao.TSysParamDao;
import com.fufan.mtsaas.modules.sysmgr.tsysparam.model.TSysParam;
import com.fufan.mtsaas.modules.newtech.xjsreviewclinicalapplicationreport.dao.XjsReviewClinicalApplicationReportDao;
import com.fufan.mtsaas.modules.newtech.xjsreviewclinicalapplicationreport.model.XjsReviewClinicalApplicationReport;
import com.fufan.mtsaas.modules.newtech.xjsreviewlimittechdoc.dao.XjsReviewLimitTechDocDao;
import com.fufan.mtsaas.modules.newtech.xjsreviewlimittechdoc.model.XjsReviewLimitTechDoc;
import com.fufan.mtsaas.modules.newtech.xjsreviewmedicaltechnology.dao.XjsReviewMedicalTechnologyDao;
import com.fufan.mtsaas.modules.newtech.xjsreviewmedicaltechnology.model.XjsReviewMedicalTechnology;
import com.fufan.mtsaas.modules.newtech.xjsreviewmedicaltechnologyevaluation.dao.XjsReviewMedicalTechnologyEvaluationDao;
import com.fufan.mtsaas.modules.newtech.xjsreviewmedicaltechnologyevaluation.model.XjsReviewMedicalTechnologyEvaluation;
import com.fufan.mtsaas.modules.newtech.xjsreviewmedicaltechnologytracking.dao.XjsReviewMedicalTechnologyTrackingDao;
import com.fufan.mtsaas.modules.newtech.xjsreviewmedicaltechnologytracking.model.XjsReviewMedicalTechnologyTracking;
import com.fufan.mtsaas.modules.newtech.xjstech.bo.request.XjsTechSendSmaRequest;
import com.fufan.mtsaas.modules.newtech.xjstech.dao.XjsTechDao;
import com.fufan.mtsaas.modules.newtech.xjstechhis.dao.XjsTechHisDao;
import com.fufan.mtsaas.modules.newtech.xjsyearaudit.bo.request.*;
import com.fufan.mtsaas.modules.newtech.xjsyearaudit.bo.response.XjsYearAuditResponse;
import com.fufan.mtsaas.modules.newtech.xjsyearaudit.bo.response.XjsYearAuditTotal;
import com.fufan.mtsaas.modules.newtech.xjsyearaudit.dao.XjsYearAuditDao;
import com.fufan.mtsaas.modules.newtech.xjsyearaudit.model.XjsYearAudit;
import com.fufan.mtsaas.modules.newtech.xjsyearaudit.service.XjsYearAuditSvc;
import com.fufan.mtsaas.modules.sysmgr.sydept.dao.SYDeptDao;
import com.fufan.mtsaas.modules.sysmgr.syuser.dao.SYuserDao;
import com.fufan.mtsaas.modules.sysmgr.syuser.model.SYuser;
import com.fufan.mtsaas.tools.AESTool;
import com.fufan.mtsaas.util.ParamUtil;
import com.fufan.mtsaas.util.SMSSender;
import com.github.pagehelper.ISelect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Liby
 * @since 2024-12-16
 */
@Service("XjsYearAuditSvcImpl")
@Slf4j
@Primary
public class XjsYearAuditSvcImpl extends ServiceImpl<XjsYearAuditDao, XjsYearAudit> implements XjsYearAuditSvc {
    /**
     * 数据库操作
     */
    @Autowired
    private XjsTechDao xjsTechDao;

    @Autowired
    private SYuserDao userDao;

    @Autowired
    private SYDeptDao deptDao;

    /**
     * 审批历史表
     */
    @Autowired
    private PProcessInfoDao pProcessInfoDao;


    @Autowired
    private TSysParamDao tsParamDao;


    /**
     * 年审表
     */
    @Autowired
    private XjsYearAuditDao xjsYearAuditDao;

    /**
     * 新项目历史表
     */
    @Autowired
    private XjsTechHisDao xjsTechHisDao;

    @Autowired
    private TSysMessageDao tsMessageDao;

    @Resource
    private XjsReviewClinicalApplicationReportDao xjsReviewClinicalApplicationReportDao;
    @Resource
    private XjsReviewMedicalTechnologyDao xjsReviewMedicalTechnologyDao;
    @Resource
    private XjsReviewMedicalTechnologyTrackingDao xjsReviewMedicalTechnologyTrackingDao;
    @Resource
    private XjsReviewMedicalTechnologyEvaluationDao xjsReviewMedicalTechnologyEvaluationDao;
    @Resource
    private XjsReviewLimitTechDocDao xjsReviewLimitTechDocDao;

    @Autowired
    private TSysLogSvc tSysLogSvc;

    @Autowired
    private SMSSender smsSender;
    @Autowired
    private ParamUtil paramUtil;
    @Autowired
    private XjsTechSvcImpl xjsTechSvc;

    @Override
    public Result<XjsYearAudit> doSave(XjsYearAuditSaveRequest entity, RequestPojo requestPojo) {
        Result<XjsYearAudit> result = new Result<>();
        Page page = new Page();

        try {
            entity.setUpdateTime(new Date());
            entity.setUpdateBy(requestPojo.getUserName());
            xjsYearAuditDao.updateById(entity);

            // 对于关联表数据，先删除，在新增
            xjsReviewClinicalApplicationReportDao.deleteByMap(new HashMap<String, Object>() {{
                put("correlation_id", entity.getId());
            }});
            xjsReviewMedicalTechnologyDao.deleteByMap(new HashMap<String, Object>() {{
                put("correlation_id", entity.getId());
            }});
            xjsReviewMedicalTechnologyTrackingDao.deleteByMap(new HashMap<String, Object>() {{
                put("correlation_id", entity.getId());
            }});
            xjsReviewMedicalTechnologyEvaluationDao.deleteByMap(new HashMap<String, Object>() {{
                put("correlation_id", entity.getId());
            }});

            // 存关联id
            if (null != entity.getClinicalApplicationReport()) {
                entity.getClinicalApplicationReport().setCorrelationId(entity.getId());
                xjsReviewClinicalApplicationReportDao.insert(entity.getClinicalApplicationReport());
            }
            if (null != entity.getMedicalTechnology()) {
                entity.getMedicalTechnology().setCorrelationId(entity.getId());
                xjsReviewMedicalTechnologyDao.insert(entity.getMedicalTechnology());
            }
            if (null != entity.getMedicalTechnologyTracking()) {
                entity.getMedicalTechnologyTracking().setCorrelationId(entity.getId());
                xjsReviewMedicalTechnologyTrackingDao.insert(entity.getMedicalTechnologyTracking());
            }
            if (null != entity.getMedicalTechnologyEvaluation()) {
                entity.getMedicalTechnologyEvaluation().setCorrelationId(entity.getId());
                xjsReviewMedicalTechnologyEvaluationDao.insert(entity.getMedicalTechnologyEvaluation());
            }

            //先删除已有数据，在插入
            xjsReviewLimitTechDocDao.deleteByCorrId(entity.getId());

            if (CollectionUtils.isNotEmpty(entity.getLimitTechDoc())) {
                for (XjsReviewLimitTechDoc item : entity.getLimitTechDoc()) {
                    item.setProjectNo(entity.getProjectNo());
                    item.setId(0);
                    item.setCorrelationId(entity.getId());
                    item.setDocType(1);
                    xjsReviewLimitTechDocDao.insert(item);
                }
            }
            if (CollectionUtils.isNotEmpty(entity.getLimitNewTechDoc())) {
                for (XjsReviewLimitTechDoc item : entity.getLimitTechDoc()) {
                    item.setProjectNo(entity.getProjectNo());
                    item.setId(0);
                    item.setCorrelationId(entity.getId());
                    item.setDocType(2);
                    xjsReviewLimitTechDocDao.insert(item);
                }
            }

            log.debug("新增数据返回 {}", entity);

            tSysLogSvc.saveLogInfo(Long.valueOf(entity.getId()), "xjsannual", "新增项目年审", "项目名称:" + entity.getName(), "新增", "成功", requestPojo);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
            result.setResData(page.setRecords(Arrays.asList(entity)));

        } catch (Exception e) {
            tSysLogSvc.saveLogInfo(Long.valueOf(entity.getId()), "xjsannual", "新增项目年审", "项目名称:" + entity.getName(), "新增", "失败", requestPojo);

            log.error("新增数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增数据出错：" + e.getMessage());
        }
        return result;
    }

    @Transactional
    @Override
    public Result doUpdate(XjsYearAuditIdRequest entity, RequestPojo requestPojo) {
        XjsYearAudit xjsYearAudit =  xjsYearAuditDao.selectById(entity.getId());
        if (null != xjsYearAudit) {

            xjsYearAudit.setAuditStatus(2);
            xjsYearAudit.setStatus(90);
            xjsYearAudit.setUpdateBy(requestPojo.getUserName());
            xjsYearAudit.setUpdateTime(new Date());
            xjsYearAuditDao.updateById(xjsYearAudit);

            // 提交流程,流转到部门负责人
            PProcessInfo pProcessInfo = new PProcessInfo();
            pProcessInfo.setCorrelationId(Long.valueOf(xjsYearAudit.getId()));
            pProcessInfo.setCreateTime(new Date());
            pProcessInfo.setTaskName("部门负责人审核");
            pProcessInfo.setCategory(2);
            pProcessInfo.setProcessStatus(90);
            pProcessInfo.setProcessBy(xjsYearAudit.getApplyManagerName());
            pProcessInfo.setProcessOper("部门负责人审核");
            pProcessInfo.setProcessUserId(xjsYearAudit.getApplyManagerId());
            pProcessInfo.setStatus(0);
            pProcessInfoDao.insert(pProcessInfo);

            // 存历史消息表
            TSysMessage tsMessage = new TSysMessage();
            tsMessage.setRelatedId(Long.valueOf(xjsYearAudit.getId()));
            tsMessage.setRelatedType("年审");
            tsMessage.setLogTitle("年审流程审批");
            tsMessage.setLogContent("您有一条" + xjsYearAudit.getName() + "年审待审批");
            tsMessage.setCreateBy(String.valueOf(xjsYearAudit.getApplyManagerId()));
            tsMessage.setCreateTime(new Date());
            tsMessage.setOperateStatus(DefaultConstant.NUM_0);
            tsMessageDao.insert(tsMessage);

            // 发短信:
            SYuser thisUser = userDao.selectById(xjsYearAudit.getApplyManagerId());
            XjsTechSendSmaRequest sendSms = new XjsTechSendSmaRequest();
            try {
                sendSms.setTel(AESTool.decrypt(thisUser.getPhoneNo()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (null != sendSms.getTel()) {
                sendSms.setCustomerID(thisUser.getUserID());
                sendSms.setCustomerName(thisUser.getName());
                sendSms.setCustomerType("1");
                sendSms.setSrvType("XJS");
                sendSms.setMessage(SMSSender.getContent(thisUser.getName(), xjsYearAudit.getName(), 90));
                smsSender.sendSms(sendSms);
            }
        }

        tSysLogSvc.saveLogInfo(Long.valueOf(xjsYearAudit.getId()), "xjsannual", "修改项目年审", "项目名称:" + xjsYearAudit.getName(), "修改", "成功", requestPojo);

        Result result = new Result();
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        return result;
    }

    @Override
    public Result doDelete(XjsYearAuditDeleteRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        // 提交
        // 1.获取原有信息，并修改状态
        XjsYearAudit xjsTech = xjsYearAuditDao.selectById(map.getId());
        if (xjsTech == null || xjsTech.getDelFlag() == 1) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg("数据已删除");
            return result;
        }
        xjsYearAuditDao.deleteById(map.getId());

        tSysLogSvc.saveLogInfo(Long.valueOf(map.getId()), "xjsannual", "删除项目年审", "项目名称:" + xjsTech.getName(), "删除", "成功", requestPojo);

        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

        return result;
    }

    @Override
    public Result doDetail(XjsYearAuditQueryByIdRequest map, RequestPojo requestPojo) {
        Result<XjsYearAuditResponse> result = new Result();
        XjsYearAudit xjsTech = xjsYearAuditDao.selectById(map.getId());
        if (null != xjsTech) {
            XjsYearAuditResponse xjsTechResponse = new XjsYearAuditResponse();
            BeanUtils.copyProperties(xjsTech, xjsTechResponse);

            List<XjsReviewClinicalApplicationReport> clinicalApplicationReportList = xjsReviewClinicalApplicationReportDao.selectByMap(new HashMap<String, Object>() {{
                put("correlation_id", map.getId());
            }});
            if (CollectionUtils.isNotEmpty(clinicalApplicationReportList)) {
                xjsTechResponse.setClinicalApplicationReport(clinicalApplicationReportList.get(0));
            }

            List<XjsReviewMedicalTechnology> xjsReviewMedicalTechnology = xjsReviewMedicalTechnologyDao.selectByMap(new HashMap<String, Object>() {{
                put("correlation_id", map.getId());
            }});
            if (CollectionUtils.isNotEmpty(xjsReviewMedicalTechnology)) {
                xjsTechResponse.setMedicalTechnology(xjsReviewMedicalTechnology.get(0));
            }

            List<XjsReviewMedicalTechnologyTracking> xjsReviewMedicalTechnologyTracking = xjsReviewMedicalTechnologyTrackingDao.selectByMap(new HashMap<String, Object>() {{
                put("correlation_id", map.getId());
            }});
            if (CollectionUtils.isNotEmpty(xjsReviewMedicalTechnologyTracking)) {
                xjsTechResponse.setMedicalTechnologyTracking(xjsReviewMedicalTechnologyTracking.get(0));
            }

            List<XjsReviewMedicalTechnologyEvaluation> xjsReviewMedicalTechnologyEvaluation = xjsReviewMedicalTechnologyEvaluationDao.selectByMap(new HashMap<String, Object>() {{
                put("correlation_id", map.getId());
            }});
            if (CollectionUtils.isNotEmpty(xjsReviewMedicalTechnologyEvaluation)) {
                xjsTechResponse.setMedicalTechnologyEvaluation(xjsReviewMedicalTechnologyEvaluation.get(0));
            }

            List<XjsReviewLimitTechDoc> xjsReviewLimitTechDocs = xjsReviewLimitTechDocDao.selectByMap(new HashMap<String, Object>() {{
                put("correlation_id", map.getId());
                put("doc_type", "1");
            }});
            if (CollectionUtils.isNotEmpty(xjsReviewLimitTechDocs)) {
                xjsTechResponse.setLimitTechDoc(xjsReviewLimitTechDocs);
            }

            List<XjsReviewLimitTechDoc> xjsNewReviewLimitTechDocs = xjsReviewLimitTechDocDao.selectByMap(new HashMap<String, Object>() {{
                put("correlation_id", map.getId());
                put("doc_type", "2");
            }});
            if (CollectionUtils.isNotEmpty(xjsNewReviewLimitTechDocs)) {
                xjsTechResponse.setLimitNewTechDoc(xjsNewReviewLimitTechDocs);
            }

            // 获取所有审批人，更新当前审批人审批状态
            PProcessInfo processFilter = new PProcessInfo();
            processFilter.setCorrelationId(Long.valueOf(xjsTech.getId()));
            processFilter.setCategory(2);
            List<PProcessInfo> pProcessInfos = pProcessInfoDao.queryAll(processFilter);


            xjsTechResponse.setProcessInfoList(pProcessInfos);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

            Page page = new Page();
            result.setResData(page.setRecords(Arrays.asList(xjsTechResponse)));
        } else {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg(ResStatus.STATUS_UNAVAILABLE_MSG);
        }
        return result;
    }

    /**
     * 获取系统参数
     *
     * @param paramName
     * @return
     */
    private TSysParam getTSysParam(String paramName) {
        TSysParam tsParam = new TSysParam();
        tsParam.setParamName(paramName);
        TSysParam info = tsParamDao.selectOne(tsParam);
        return info;
    }

    @Transactional
    @Override
    public Result doApprove(XjsYearAuditApproveRequest map, RequestPojo requestPojo) {
        Result result = new Result<>();
        // 1.获取当前项目信息,当前节点信息
        XjsYearAudit xjsYearAudit =  xjsYearAuditDao.selectById(map.getId());

        String shortName = paramUtil.getTSysParam("HOSPITAL_NAME");

        // 2.编辑当前审核人审核状态
        // 所有的流程状态
        TSysParam status = getTSysParam(shortName + "_XJS_CIRCULATION_STATUS");
        List<CirculationStatusBo> circleStatus = null;
        if (status != null) {
            String statusJson = status.getParamValue();
            ObjectMapper mapper = new ObjectMapper();
            try {
                circleStatus = mapper.readValue(statusJson, new TypeReference<List<CirculationStatusBo>>() {
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (CollectionUtils.isEmpty(circleStatus)) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg(ResStatus.STATUS_UNAVAILABLE_MSG);
            return result;
        }
        // 当前节点
        CirculationStatusBo thisStatus = circleStatus.stream().filter(a -> a.getKey().equals(xjsYearAudit.getStatus())).findFirst().orElse(null);
        if (null == thisStatus) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg(ResStatus.STATUS_UNAVAILABLE_MSG);
            return result;
        }

        // 此数据用户信息
        SYuser thisUser = userDao.selectById(xjsYearAudit.getApplyUserId());

        // 当前用户ID
        String staffId = requestPojo.getSysId();
        // 获取所有审批人，更新当前审批人审批状态
        PProcessInfo processFilter = new PProcessInfo();
        processFilter.setCorrelationId(Long.valueOf(xjsYearAudit.getId()));
        List<PProcessInfo> pProcessInfos = pProcessInfoDao.queryAll(processFilter);
        if (CollectionUtils.isNotEmpty(pProcessInfos)) {
            for (PProcessInfo item : pProcessInfos) {
                if (staffId.equals(String.valueOf(item.getProcessUserId())) && xjsYearAudit.getStatus().equals(item.getProcessStatus())) {
                    item.setStatus(1);
                    item.setRemarks(map.getRemarks());
                    item.setUpdateTime(new Date());
                    item.setTask(map.getTask());
                    item.setAuditStatus(map.getAuditStatus());
                    pProcessInfoDao.updateById(item);

                    // 发短信:  定制化： 流转中的任意一个结点完成审批后是驳回拒绝的结果
                    XjsTechSendSmaRequest sendSms = new XjsTechSendSmaRequest();
                    try {
                        sendSms.setTel(AESTool.decrypt(thisUser.getPhoneNo()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (null != sendSms.getTel()) {
                        sendSms.setCustomerID(thisUser.getUserID());
                        sendSms.setCustomerName(thisUser.getName());
                        sendSms.setCustomerType("1");
                        sendSms.setSrvType("XJS");
                        sendSms.setMessage(SMSSender.getContent(thisUser.getName(), xjsYearAudit.getName(),110));
                        smsSender.sendSms(sendSms);
                    }

                    // 存历史消息表
                    TSysMessage tsMessage = new TSysMessage();
                    tsMessage.setRelatedId(Long.valueOf(xjsYearAudit.getId()));
                    tsMessage.setRelatedType("年审");
                    tsMessage.setLogTitle("年审流程审批");
                    String content = DefaultConstant.NUM_1.equals(item.getAuditStatus()) ? "审批通过" : "审批驳回";
                    tsMessage.setLogContent(xjsYearAudit.getName() + "年审流程审批" + thisStatus.getName() + content);
                    tsMessage.setCreateBy(String.valueOf(xjsYearAudit.getApplyUserId()));
                    tsMessage.setCreateTime(new Date());
                    tsMessage.setOperateStatus(DefaultConstant.NUM_0);
                    tsMessageDao.insert(tsMessage);

                    // 不是继续状态，则视为终止，不进行任何操作
                    if (!DefaultConstant.NUM_1.equals(item.getAuditStatus())) {
                        // 驳回，不进行任何操作
                        xjsYearAudit.setAuditStatus(DefaultConstant.NUM_4);
                        xjsYearAuditDao.updateById(xjsYearAudit);
                        result.setResStatus(ResStatus.STATUS_SUCCESS);
                        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
                        return result;
                    }
                }
            }
        }


        Double xjsScore = DefaultConstant.NUM_67;
        try {
            TSysParam scoreParam = getTSysParam("XJS_SCORE");
            if (Objects.nonNull(scoreParam) && Objects.nonNull(scoreParam.getParamValue())) {
                xjsScore = Double.valueOf(scoreParam.getParamValue());
            }
        } catch (Exception ex) {
        }

        //  3.如果当前节点多人审批，需要通过投票的方式，当通过人数大于百分之50时，确定流程是否进行下一步流转
        // 当前流程总人数
        Long total = pProcessInfos.stream().filter(a -> null != a.getProcessStatus() && a.getProcessStatus().equals(xjsYearAudit.getStatus())).count();
        // 通过人数
        Long pass = pProcessInfos.stream().filter(a -> null != a.getProcessStatus() && a.getProcessStatus().equals(a.getStatus()) && DefaultConstant.NUM_1.equals(a.getAuditStatus())).count();
//        Long pass = pProcessInfos.stream().filter(a -> DefaultConstant.NUM_1.equals(a.getAuditStatus())).count();
        if (pass.doubleValue() / total.doubleValue() >= xjsScore) {

            // 当前节点若还有其他人待审批的改为无需处理
            pProcessInfos.stream().filter(a -> DefaultConstant.NUM_0.equals(a.getStatus()) &&
                    null != a.getProcessStatus() && a.getProcessStatus().equals(xjsYearAudit.getStatus())).forEach(a -> {
                a.setStatus(2);
                a.setUpdateTime(new Date());
                pProcessInfoDao.updateById(a);
            });

            //获取流转人员信息，新增下一次需要审核的人员名单
            TSysParam info = getTSysParam(shortName + "_XJS_FLOW");
            if (info != null) {
                // 数据类型转换
                String infoJson = info.getParamValue();
                ObjectMapper mapper = new ObjectMapper();
                List<ProcessItemBo> processItems = null;
                try {
                    processItems = mapper.readValue(infoJson, new TypeReference<List<ProcessItemBo>>() {
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (null == processItems || null == circleStatus) {
                    result.setResStatus(ResStatus.STATUS_SUCCESS);
                    result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
                    return result;
                }

                // 没有下个节点了
                if (null == thisStatus.getNextKey()) {
                    // 5.修改当前项目的下一个节点状态为110,结束
                    xjsYearAudit.setStatus(110);
                    xjsYearAudit.setAuditStatus(DefaultConstant.NUM_3);
                    xjsYearAuditDao.updateById(xjsYearAudit);
                    result.setResStatus(ResStatus.STATUS_SUCCESS);
                    result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
                    return result;
                }
                // 获取下一个节点
                CirculationStatusBo nextStatus = circleStatus.stream().filter(a -> a.getKey().equals(thisStatus.getNextKey())).findFirst().orElse(null);
                for (ProcessItemBo item : processItems) {
                    // 当前节点信息
                    System.out.println("Process: " + item.getProcess());
                    // 当前节点的下一个节点
                    if (null == item.getProcess() || !item.getProcess().equals(thisStatus.getNextKey())) {
                        continue;
                    }
                    List<SYuser> syuserList = new ArrayList<>();
                    // 当前节点所涉及到的人员ID
                    if (item.getSyuser() != null) {
                        for (ProcessItemBo.SyUserId user : item.getSyuser()) {
                            System.out.println("User ID: " + user.getId());
                            SYuser sYuser = userDao.selectById(user.getId());
                            if (sYuser == null) {
                                continue;
                            }
                            syuserList.add(sYuser);
                        }
                    }
                    // 当前节点所涉及到的部门ID
                    if (CollectionUtils.isNotEmpty(item.getSydept())) {
                        for (ProcessItemBo.SyDeptId dept : item.getSydept()) {
                            System.out.println("Manager: " + dept.getManager());
                            Page page = new Page();
                            HashMap userFilter = new HashMap<>();
                            userFilter.put("DepID", dept.getManager());
                            List<SYuser> syuser = userDao.selectList(page, userFilter);
                            syuserList.addAll(syuser);
                        }
                    }

                    // 当前节点所涉及到的组ID
                    if (CollectionUtils.isNotEmpty(item.getSygrouph())) {
                        for (ProcessItemBo.SyGroupId group : item.getSygrouph()) {
                            System.out.println("Group ID: " + group.getId());
                            Page page = new Page();
                            HashMap userFilter = new HashMap<>();
                            userFilter.put("UserGroupID", group.getId());
                            List<SYuser> syuser = userDao.selectList(page, userFilter);
                            syuserList.addAll(syuser);
                        }

                        syuserList = xjsTechSvc.getGroupRelatedUsers(syuserList, item);
                    }

                    // 4.存储下一个阶段的审核人
                    for (SYuser sYuser : syuserList) {
                        //20250223：判定是否已存在（用户+流程节点）
                        total = pProcessInfos.stream().filter(a -> null != a.getProcessStatus()
                                && a.getProcessStatus().equals(nextStatus.getKey())
                                && a.getProcessUserId().equals(Long.valueOf(sYuser.getId()))).count();
                        if (total > 0) {
                            continue;
                        }

                        // 提交流程,流转到部门负责人
                        PProcessInfo pProcessInfo = new PProcessInfo();
                        pProcessInfo.setCorrelationId(Long.valueOf(xjsYearAudit.getId()));
                        pProcessInfo.setCreateTime(new Date());
                        pProcessInfo.setTaskName(nextStatus.getName() + "审核");
                        pProcessInfo.setCategory(2);
                        pProcessInfo.setProcessStatus(nextStatus.getKey());
                        pProcessInfo.setProcessBy(sYuser.getName());
                        pProcessInfo.setProcessOper(nextStatus.getName() + "审核");
                        pProcessInfo.setProcessUserId(Long.valueOf(sYuser.getId()));
                        pProcessInfo.setStatus(0);
                        pProcessInfoDao.insert(pProcessInfo);

                        // 存历史消息表
                        TSysMessage tsMessage = new TSysMessage();
                        tsMessage.setRelatedId(Long.valueOf(xjsYearAudit.getId()));
                        tsMessage.setRelatedType("年审");
                        tsMessage.setLogTitle("年审流程审批");
                        tsMessage.setLogContent("您有一条" + xjsYearAudit.getName() + "年审待审批");
                        tsMessage.setCreateBy(String.valueOf(sYuser.getId()));
                        tsMessage.setCreateTime(new Date());
                        tsMessage.setOperateStatus(DefaultConstant.NUM_0);
                        tsMessageDao.insert(tsMessage);

                        // 发送短信：给相应的下一阶段审核人
                        XjsTechSendSmaRequest sendSms = new XjsTechSendSmaRequest();
                        try {
                            sendSms.setTel(AESTool.decrypt(sYuser.getPhoneNo()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (null != sendSms.getTel()) {
                            sendSms.setCustomerID(sYuser.getUserID());
                            sendSms.setCustomerName(sYuser.getName());
                            sendSms.setCustomerType("1");
                            sendSms.setSrvType("XJS");
                            sendSms.setMessage(SMSSender.getContent(sYuser.getName(), xjsYearAudit.getName(), nextStatus.getKey()));
                            smsSender.sendSms(sendSms);
                        }
                    }
                }

                // 5.修改当前项目的下一个节点状态
                xjsYearAudit.setStatus(nextStatus.getKey());
                xjsYearAuditDao.updateById(xjsYearAudit);

                String content = DefaultConstant.NUM_1.equals(xjsYearAudit.getAuditStatus()) ? "审批通过" : "审批驳回";

                tSysLogSvc.saveLogInfo(Long.valueOf(xjsYearAudit.getId()), "xjsannual", "审批项目年审", "项目名称:" + xjsYearAudit.getName(), content, "成功", requestPojo);
            }
        }

        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        return result;
    }

    /**
     * 我申请的年审
     * @param map
     * @param requestPojo
     * @return
     */
    @Override
    public Result<XjsYearAuditResponse> doMyAuditApplication(XjsYearAuditQueryRequest map, RequestPojo requestPojo) {
        Result<XjsYearAuditResponse> result = new Result<>();

        // 当前用户ID
        String staffId = requestPojo.getSysId();
        map.setStaffId(staffId);

        // 我申请的年审， 通过数据类型区分
        // 查看已经开通，与自己相关的
        map.setQueryType("myAuditApplication");

        Page<XjsYearAuditResponse> page = new Page<>();
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                xjsYearAuditDao.selectByPage(page, map);
            }
        });

        // 分页
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        //分页查询
        List<XjsYearAuditResponse> list = xjsYearAuditDao.selectByPage(page, map);

        page.setRecords(list);
        page.setTotal((int) total);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    /**
     * 我的年审草稿
     * @param map
     * @param requestPojo
     * @return
     */
    @Override
    public Result<XjsYearAuditResponse> doMyDraftQuery(XjsYearAuditQueryRequest map, RequestPojo requestPojo) {
        Result<XjsYearAuditResponse> result = new Result<>();

        // 当前用户ID
        String staffId = requestPojo.getSysId();
        map.setStaffId(staffId);

        // 我的年审草稿
        map.setQueryType("doMyDraftQuery");

        Page<XjsYearAuditResponse> page = new Page<>();
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                xjsYearAuditDao.selectByPage(page, map);
            }
        });

        // 分页
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        //分页查询
        List<XjsYearAuditResponse> list = xjsYearAuditDao.selectByPage(page, map);

        page.setRecords(list);
        page.setTotal((int) total);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    /**
     * 已完成项目年审
     * @param map
     * @param requestPojo
     * @return
     */
    @Override
    public Result<XjsYearAuditResponse> doCompletedProjectAudit(XjsYearAuditQueryRequest map, RequestPojo requestPojo) {
        Result<XjsYearAuditResponse> result = new Result<>();

        // 当前用户ID
        String staffId = requestPojo.getSysId();
        map.setStaffId(staffId);

        // 已完成项目年审
        map.setQueryType("completedProjectAudit");

        Page<XjsYearAuditResponse> page = new Page<>();
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                xjsYearAuditDao.selectByPage(page, map);
            }
        });

        // 分页
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        //分页查询
        List<XjsYearAuditResponse> list = xjsYearAuditDao.selectByPage(page, map);

        page.setRecords(list);
        page.setTotal((int) total);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    /**
     * 待审核项目年审
     * @param map
     * @param requestPojo
     * @return
     */
    @Override
    public Result<XjsYearAuditResponse> doPendingStageReviewConfirmation(XjsYearAuditQueryRequest map, RequestPojo requestPojo) {
        Result<XjsYearAuditResponse> result = new Result<>();

        // 当前用户ID
        String staffId = requestPojo.getSysId();
        map.setStaffId(staffId);

        // 待审核项目年审
        map.setQueryType("pendingStageReviewConfirmation");

        Page<XjsYearAuditResponse> page = new Page<>();
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                xjsYearAuditDao.selectByProcessAndPage(page, map);
            }
        });

        // 分页
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        //分页查询
        List<XjsYearAuditResponse> list = xjsYearAuditDao.selectByProcessAndPage(page, map);

        page.setRecords(list);
        page.setTotal((int) total);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    /**
     * 已确认的项目年审
     * @param map
     * @param requestPojo
     * @return
     */
    @Override
    public Result<XjsYearAuditResponse> doConfirmedStageReview(XjsYearAuditQueryRequest map, RequestPojo requestPojo) {
        Result<XjsYearAuditResponse> result = new Result<>();

        // 当前用户ID
        String staffId = requestPojo.getSysId();
        map.setStaffId(staffId);

        // 已确认的项目年审
        map.setQueryType("confirmedStageReview");

        Page<XjsYearAuditResponse> page = new Page<>();
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                xjsYearAuditDao.selectByProcessAndPage(page, map);
            }
        });

        // 分页
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        //分页查询
        List<XjsYearAuditResponse> list = xjsYearAuditDao.selectByProcessAndPage(page, map);

        page.setRecords(list);
        page.setTotal((int) total);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    @Override
    public Result<XjsYearAuditResponse> doYearAuditApplication(XjsYearAuditQueryRequest map, RequestPojo requestPojo) {
        Result<XjsYearAuditResponse> result = new Result<>();

        // 当前用户ID
//        String staffId = requestPojo.getSysId();
//        map.setStaffId(staffId);

        // 我申请的年审， 通过数据类型区分
        // 查看已经开通，与自己相关的
//        map.setQueryType("myAuditApplication");

        Page<XjsYearAuditResponse> page = new Page<>();
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                xjsYearAuditDao.selectByYearAuditPage(page, map);
            }
        });

        // 分页
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        //分页查询
        List<XjsYearAuditResponse> list = xjsYearAuditDao.selectByYearAuditPage(page, map);

        page.setRecords(list);
        page.setTotal((int) total);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    @Override
    public Result<XjsYearAuditTotal> doYearAuditTotal(){
        Result<XjsYearAuditTotal> result = new Result<>();
        XjsYearAuditTotal yearAuditTotal = new XjsYearAuditTotal();
        //总数
        Integer applyTotal = xjsYearAuditDao.selectTotal(0);
        yearAuditTotal.setApplyTotal(applyTotal);
        Integer runTotal = xjsYearAuditDao.selectTotal(2);
        yearAuditTotal.setRunTotal(runTotal);
        Integer finishTotal = xjsYearAuditDao.selectTotal(3);
        yearAuditTotal.setFinishTotal(finishTotal);

        Page page = new Page();
        result.setResData(page.setRecords(Arrays.asList(yearAuditTotal)));
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

        return result;
    }

}
